package com.example.devinfan.criminalintent.Activity;

import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;

import com.example.devinfan.criminalintent.model.Crime;
import com.example.devinfan.criminalintent.Fragment.CrimeFragment;
import com.example.devinfan.criminalintent.model.CrimeLab;
import com.example.devinfan.criminalintent.R;

import java.util.ArrayList;
import java.util.UUID;

public class CrimePagerActivity extends ActionBarActivity{
    private ArrayList<Crime> mCrimes;
    public static CrimePagerAdapter mCrimePagerAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        ViewPager viewPager = new ViewPager(this);
        viewPager.setId(R.id.viewPager);
        setContentView(viewPager);
        mCrimes = CrimeLab.get(this).getCrimes();


        //设置Adapter
        FragmentManager fm = getSupportFragmentManager();
        mCrimePagerAdapter = new CrimePagerAdapter(fm);
        viewPager.setAdapter(mCrimePagerAdapter);

        //改变标题
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Crime crime = mCrimes.get(position);
                if (crime.getTitle() != null) setTitle(crime.getTitle());
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        //按照所点到的某个Crime,显示相应的Crime
        UUID crimeId = (UUID)getIntent().getSerializableExtra(CrimeFragment.EXTRA_CRIME_ID);
        for(int i = 0; i < mCrimes.size(); i++){
            if (mCrimes.get(i).getId().equals(crimeId)) {
                viewPager.setCurrentItem(i);break;
            }
        }
    }

    public class CrimePagerAdapter extends FragmentStatePagerAdapter {
        public CrimePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Crime crime = mCrimes.get(position);
            return CrimeFragment.newInstance(crime.getId());
        }

        @Override
        public int getCount() {
            return mCrimes.size();
        }
    }
}
